package net.lesscoding.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.lesscoding.entity.storage.StorageTbl;
import net.lesscoding.mapper.StorageMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author eleven
 * @date 2025/4/16 14:21
 * @apiNote
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class StorageService extends ServiceImpl<StorageMapper, StorageTbl> {

    private final StorageMapper storageMapper;

    @Transactional
    public Integer deduct(String goodsCode, Integer count) {
        StorageTbl storageTbl = storageMapper.selectOne(new LambdaQueryWrapper<StorageTbl>()
                .eq(StorageTbl::getGoodsCode, goodsCode));
        if (storageTbl == null) {
            throw  new RuntimeException("商品不存在");
        }
        if (storageTbl.getCount() < count) {
            throw new RuntimeException("商品库存不足");
        }
        return storageMapper.deduct(goodsCode, count);
    }
}
